package com.example.gugongticket.service.impl;

import java.text.SimpleDateFormat;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.management.Query;
import javax.transaction.Transactional;

import com.example.gugongticket.dao.OrdersRepository;
import com.example.gugongticket.dao.SalesStatisticsRepository;
import com.example.gugongticket.dao.TicketRepository;
import com.example.gugongticket.dao.UserRepository;
import com.example.gugongticket.entity.Orders;
import com.example.gugongticket.entity.SalesStatistics;
import com.example.gugongticket.entity.Ticket;
import com.example.gugongticket.entity.User;
import com.example.gugongticket.service.TicketSalesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 实现门票销售服务的类
 */
@Service
public class TicketSalesServiceImpl implements TicketSalesService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private OrdersRepository OrdersRepository;

    @Autowired
    private SalesStatisticsRepository salesStatisticsRepository;

    @Autowired
    private TicketRepository ticketRepository;

    /**
     * 注册用户
     */
    @Override
    public void registerUser(String username, String password, String email, String phone) {
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setEmail(email);
        user.setPhone(phone);
        userRepository.save(user);
    }

   /**
    * 用户登录
    */
   @Override
   public int login(String username, String password) {
       List<User> users = userRepository.findByUsername(username);
       if (!users.isEmpty()) {
           User user = users.get(0);
           if (password.equals(user.getPassword())) {
               return 0;
           } else {
               return 1;
           }
       } else {
           return 2;
       }
   }

@Transactional
/**
 * 预定大门票
 */
public void bookGateTickets(int userId, int quantity, double totalPrice, Date date) {
    // 检查日期范围
    Date today = new Date();
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(today);
    calendar.add(Calendar.DAY_OF_YEAR, 14);
    Date maxDate = calendar.getTime();

    if (date.before(today) || date.after(maxDate)) {
        throw new IllegalArgumentException("只能预定今天或者未来14天内的门票");
    }

    if (quantity <= 0 || totalPrice <= 0) {
        throw new IllegalArgumentException("数量和总价必须大于零");
    }

    int ticketId = 1; // 假设这是大门票的ID
    Ticket ticket = ticketRepository.findById(ticketId).orElse(null);
    if (ticket == null || quantity > ticket.getDailyRemaining()) {
        throw new IllegalArgumentException("购买数量超过可用余票");
    }

    Orders orders = new Orders();
    orders.setUserID(userId);
    orders.setTicketId(ticketId);
    orders.setQuantity(quantity);
    orders.setTotalPrice(totalPrice);
    orders.setStatus("Paid");
    orders.setDate(date);

    OrdersRepository.save(orders);

    // 更新门票的剩余数量
    updateTicketDailyRemaining(ticketId, quantity);
}

/**
 * 预定展览票
 */
@Override
@Transactional
public void bookExhibitionTickets(int userId, Ticket.TicketType type, int quantity, double totalPrice, Date date) {
    // 检查日期范围
    Date today = new Date();
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(today);
    calendar.add(Calendar.DAY_OF_YEAR, 14);
    Date maxDate = calendar.getTime();

    if (date.before(today) || date.after(maxDate)) {
        throw new IllegalArgumentException("只能预定今天或者未来14天内的门票");
    }

    // 检查用户是否已购买大门票
    boolean hasBoughtGateTicket = OrdersRepository.findByUserid(userId).stream()
        .anyMatch(order -> order.getTicketId() == 1); // 大门票的ID为1

    if (!hasBoughtGateTicket) {
        throw new IllegalArgumentException("必须先购买大门票才能购买展览票");
    }

    int ticketId = getTicketIdByType(type);
    Ticket ticket = ticketRepository.findById(ticketId).orElse(null);
    if (ticket == null || quantity > ticket.getDailyRemaining()) {
        throw new IllegalArgumentException("购买数量超过可用余票");
    }

    Orders orders = new Orders();
    orders.setUserID(userId);
    orders.setTicketId(ticketId);
    orders.setQuantity(quantity);
    orders.setTotalPrice(totalPrice);
    orders.setStatus("Paid");
    orders.setDate(date);
    OrdersRepository.save(orders);

    // 更新门票的剩余数量
    updateTicketDailyRemaining(ticketId, quantity);
}


/**
 * 退款处理
 */
@Override
@Transactional
public void refundTicket(int ordersId) {
    Orders orders = OrdersRepository.findById(ordersId).orElse(null);

    // 检查订单是否存在以及状态是否合法
    if (orders == null) {
        throw new IllegalArgumentException("订单不存在");
    }

    String status = orders.getStatus().toLowerCase(); // 统一状态格式
    if (!"paid".equals(status)) {
        throw new IllegalArgumentException("订单状态不合法，无法退款");
    }

    OrdersRepository.deleteById(ordersId);
    updateSalesStatisticsOnRefund(orders);
    updateRefundTicketDailyRemaining(orders.getTicketId(), orders.getQuantity());
}

/**
 * 获取用户的预订记录
 */
@Override
public List<Orders> getBookingRecords(int userId) {
    List<Orders> orders = OrdersRepository.findByUserid(userId);

    // 检查是否成功获取到预订记录
    if (orders != null && !orders.isEmpty()) {
        System.out.println("Successfully retrieved booking records for user ID " + userId + ":");
        for (Orders order : orders) {
            Instant instant = order.getDate().toInstant();
            ZonedDateTime zonedDateTime = instant.atZone(ZoneOffset.UTC);
            ZonedDateTime adjustedDateTime = zonedDateTime.plusHours(8);
            order.setDate(java.sql.Timestamp.from(adjustedDateTime.toInstant()));
            System.out.println(order); // 输出每条预订记录
        }
    } else {
        System.out.println("No booking records found for user ID " + userId + ".");
    }

    return orders;
}

/**
 * 获取每日剩余门票数量
 */
@Override
public int getDailyRemainingTickets(Ticket.TicketType type) {
    int id=getTicketIdByType(type);
    Ticket ticket = ticketRepository.findById(getTicketIdByType(type)).orElse(null);
     int remain=ticket.getDailyRemaining();
        return ticket!= null? ticket.getDailyRemaining() : 0;

}

/**
 * 管理员根据选项查找用户
 */
    //管理员逻辑
    @Override
public List<User> findUsersByOptions(String option, String value) {
    if (value == null || value.trim().isEmpty()) {
        throw new IllegalArgumentException("查询值不能为空");
    }

    switch (option.toLowerCase()) { // 统一选项格式
        case "userid":
            try {
                return userRepository.findByUserId(Integer.parseInt(value));
            } catch (NumberFormatException e) {
                throw new IllegalArgumentException("无效的用户ID格式");
            }
        case "username":
            return userRepository.findByUsername(value);
        case "email":
            return userRepository.findByEmail(value);
        case "phone":
            return userRepository.findByPhone(value);
        default:
            throw new IllegalArgumentException("无效的查询选项");
    }
}

/**
 * 获取每日销售统计
 */
    @Override
    public List<SalesStatistics> getDailySalesStatistics(Date date) {
        SimpleDateFormat originalFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
        SimpleDateFormat targetFormat = new SimpleDateFormat("yyyy-MM-dd");

        // 格式化原始 Date 对象为目标格式字符串
        String formattedDateStr = targetFormat.format(date);

        return salesStatisticsRepository.findBySDate(formattedDateStr);
    }

    /**
     * 获取每月销售统计
     */
    @Override
    public List<SalesStatistics> getMonthlySalesStatistics(Date startDate, Date endDate) {
//        SimpleDateFormat originalFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
//        SimpleDateFormat targetFormat = new SimpleDateFormat("yyyy-MM-dd");
//
//        // 格式化原始 Date 对象为目标格式字符串
//        String formattedDateStr1 = targetFormat.format(startDate);
//        String formattedDateStr2 = targetFormat.format(endDate);
        return salesStatisticsRepository.findByDateBetween(startDate,endDate );
    }

    /**
     * 获取每年销售统计
     */
    @Override
    public List<SalesStatistics> getYearlySalesStatistics(int year) {
        // 获取指定年份的开始日期和结束日期
        LocalDate startDate = LocalDate.of(year, 1, 1);
        LocalDate endDate = LocalDate.of(year, 12, 31);

        // 将LocalDate转换为Date类型
        Date start = Date.from(startDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
        Date end = Date.from(endDate.atTime(23, 59, 59).atZone(ZoneId.systemDefault()).toInstant());

        // 使用Spring Data JPA的方法查询并返回结果
        return salesStatisticsRepository.findByDateBetween(start, end);
    }

    /**
     * 获取总销售额
     */
    @Override
    public double getTotalSales() {
        // 查询所有的销售统计数据
        List<SalesStatistics> allStatistics = salesStatisticsRepository.findAll();
        double totalSales = 0.0;

        for (SalesStatistics stat : allStatistics) {
            totalSales += stat.getTotalSales();
        }

        return totalSales;
    }

//    @Override
//    public void insertDailyTicketData(Ticket.TicketType type, int quantity) {
//        // 根据门票类型获取当前日期的销售统计数据，如果不存在则创建
//        Date today = new Date();
//        SalesStatistics stats = salesStatisticsRepository.findByDate(today);
//        if (stats == null) {
//            stats = new SalesStatistics();
//            stats.setDate(today);
//        }
//
//        // 根据门票类型更新销售数量
//        switch (type) {
//            case GATE:
//                stats.setGateTicketsSold(stats.getGateTicketsSold() + quantity);
//                break;
//            case EXHIBITION1:
//                stats.setExhibition1TicketsSold(stats.getExhibition1TicketsSold() + quantity);
//                break;
//            case EXHIBITION2:
//                stats.setExhibition2TicketsSold(stats.getExhibition2TicketsSold() + quantity);
//                break;
//            case EXHIBITION1_AND_2:
//                stats.setExhibition1And2TicketsSold(stats.getExhibition1And2TicketsSold() + quantity);
//                break;
//        }
//
//        // 更新总销售额（假设门票价格已经在其他地方定义好）
//        double ticketPrice = getTicketPriceByType(type);
//        stats.setTotalSales(stats.getTotalSales() + (quantity * ticketPrice));
//
//        // 保存销售统计数据
//        salesStatisticsRepository.save(stats);
//    }

/**
 * 插入每日门票数据
 */
    @Transactional
    public void insertDailyTicketData(Ticket.TicketType ticketType, int quantity) {
        Ticket ticket = ticketRepository.findByType(ticketType);
        if (ticket!= null) {
            ticket.setDailyRemaining(quantity);
            ticketRepository.save(ticket);
        }
    }

    /**
     * 根据门票类型获取门票价格
     */
    private double getTicketPriceByType(Ticket.TicketType type) {
        // 根据门票类型从门票仓库中查找对应的门票实体
        Ticket ticket = ticketRepository.findById(getTicketIdByType(type)).orElse(null);
        return ticket!= null? ticket.getPrice() : 0.0;
    }

    /**
     * 根据门票类型获取对应的门票ID
     */
    private int getTicketIdByType(Ticket.TicketType type) {
        switch (type) {
            case GATE:
                return 1;
            case EXHIBITION1:
                return 2;
            case EXHIBITION2:
                return 3;
            case EXHIBITION1_AND_2:
                return 4;
            default:
                return -1;
        }
    }

    /**
     * 根据门票ID获取门票类型
     */
    private Ticket.TicketType getTicketTypeById(int ticketId) {
        switch (ticketId) {
            case 1:
                return Ticket.TicketType.GATE;
            case 2:
                return Ticket.TicketType.EXHIBITION1;
            case 3:
                return Ticket.TicketType.EXHIBITION2;
            case 4:
                return Ticket.TicketType.EXHIBITION1_AND_2;
            default:
                return null;
        }
    }

//    private void updateSalesStatistics(Orders orders) {
//        Ticket.TicketType ticketType = getTicketTypeById(orders.getTicketId());
//        double ticketPrice = orders.getTotalPrice();
//        // 使用 java.sql.Date 只提取日期部分
//        java.sql.Date sqlDate = new java.sql.Date(orders.getDate().getTime());
//        System.out.println(sqlDate);
//        SalesStatistics salesStatistics = salesStatisticsRepository.findByDate(sqlDate);
//
//        if (salesStatistics == null) {
//            salesStatistics = new SalesStatistics();
//            salesStatistics.setDate(orders.getDate());
//            salesStatistics.setGateTicketsSold(0);  // 初始化其他字段
//            salesStatistics.setExhibition1TicketsSold(0);
//            salesStatistics.setExhibition2TicketsSold(0);
//            salesStatistics.setExhibition1And2TicketsSold(0);
//            salesStatistics.setTotalSales(0.0);
//        }
//
//        switch (ticketType) {
//            case GATE:
//                salesStatistics.setGateTicketsSold(salesStatistics.getGateTicketsSold() + orders.getQuantity());
//                break;
//            case EXHIBITION1:
//                salesStatistics.setExhibition1TicketsSold(salesStatistics.getExhibition1TicketsSold() + orders.getQuantity());
//                break;
//            case EXHIBITION2:
//                salesStatistics.setExhibition2TicketsSold(salesStatistics.getExhibition2TicketsSold() + orders.getQuantity());
//                break;
//            case EXHIBITION1_AND_2:
//                salesStatistics.setExhibition1And2TicketsSold(salesStatistics.getExhibition1And2TicketsSold() + orders.getQuantity());
//                break;
//        }
//
//        salesStatistics.setTotalSales(salesStatistics.getTotalSales() + ticketPrice);
//        salesStatisticsRepository.save(salesStatistics);
//    }

/**
 * 更新销售统计数据以反映退款
 */
    private void updateSalesStatisticsOnRefund(Orders orders) {

//        Date originalDate = orders.getDate();
//        LocalDate localDate = originalDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
//        String formattedDate = localDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));

        // 查找当天的销售统计数据，如果不存在则创建一个新的
        SalesStatistics salesStatistics = salesStatisticsRepository.findByDate(orders.getDate());
        if (salesStatistics == null) {
            salesStatistics = new SalesStatistics();
            salesStatistics.setDate(orders.getDate());
        }

        // 根据订单中的门票类型更新销售统计数据
        Ticket ticket = ticketRepository.findById(orders.getTicketId()).orElse(null);
        if (ticket!= null) {
            switch (ticket.getType()) {
                case GATE:
                    salesStatistics.setGateTicketsSold(salesStatistics.getGateTicketsSold() - orders.getQuantity());
                    break;
                case EXHIBITION1:
                    salesStatistics.setExhibition1TicketsSold(salesStatistics.getExhibition1TicketsSold() - orders.getQuantity());
                    break;
                case EXHIBITION2:
                    salesStatistics.setExhibition2TicketsSold(salesStatistics.getExhibition2TicketsSold() - orders.getQuantity());
                    break;
                case EXHIBITION1_AND_2:
                    salesStatistics.setExhibition1And2TicketsSold(salesStatistics.getExhibition1And2TicketsSold() - orders.getQuantity());
                    break;
            }
            // 更新总销售额
            salesStatistics.setTotalSales(salesStatistics.getTotalSales() - orders.getTotalPrice());

            // 保存更新后的销售统计数据
            salesStatisticsRepository.save(salesStatistics);
        }
    }

    /**
     * 更新门票剩余数量
     */
    private void updateTicketDailyRemaining(int ticketId, int quantity) {
        Ticket ticket = ticketRepository.findById(ticketId).orElse(null);
        if (ticket!= null) {
            ticket.setDailyRemaining(ticket.getDailyRemaining()-quantity);
            ticketRepository.save(ticket);
        }
    }

    /**
     * 更新退款后的门票剩余数量
     */
    private void updateRefundTicketDailyRemaining(int ticketId, int quantity) {
        Ticket ticket = ticketRepository.findById(ticketId).orElse(null);
        if (ticket!= null) {
            ticket.setDailyRemaining(ticket.getDailyRemaining()+quantity);
            ticketRepository.save(ticket);
        }
    }
}
